/**
 * 
 */
import Fields from '../utils/wt-model-field';
import TimeUtils from '../utils/wt-time-utils';
import FormUtils from '../utils/wt-form-utils';
import OSS from '../utils/oss';

export default {
	/*
	 * 当一条记录被查询到时，应调用buildObject来进行数据预处理
	 */
	buildObject: function(model, data) {
		let fields = model.fields;
		for (let i = 0; i < fields.length; i ++) {
			let field = fie[i];
			if (field.builder) {
				field.builder(data);
			}
		}
	},
	cloneObject: function(data) {
		if (data == null) {
			return data;
		}
		let clone = {};
		for (let item in data) {
			clone[item] = data[item];
		}
		return clone;
	},
	createDefaultObject: function(model) {
		let fields = model.fields;
		let data = {};
		for (let i = 0; i < fields.length; i ++) {
			let field = fields[i];
			if (field.noSave) {
				continue;
			}
			let value = null;
			if (field.default != null) {
				value = field.default;
			}
			else {
				let type = field.type;
				if (type == Fields.types.date || type == Fields.types.time
				 || type == Fields.types.datetime) {
					value = new Date();
					value.setHours(0);
					value.setMinutes(0);
					value.setSeconds(0);
					value.setMilliseconds(0);
				}
				else if (type == Fields.types.number) {
					value = '';
				}
				else if (type == Fields.types.text || type == Fields.types.textarea) {
					value = '';
				}
				else if (type == Fields.types.images) {
					value = [];
				}
				else if (type == Fields.types.select) {
					if (field.multiple) {
						value = [];
					}
					else {
						value = '';
					}
				}
				else {
					value = null;
				}
			}
			data[field.tableName] = value;
		}
		return data;
	},
	getIdValueFromQueryResult: function(model, data) {
		let idField = model.id_field;
		if (idField === undefined) {
			idField = {};
		}
		if (idField.tableName === undefined) {
			idField.tableName = 'id';
		}
		return data[idField.tableName];
	},
	buildQueryExtraParams: function(config, paramsData, existingForm) {
		let params = null;
		let requiredParams = config.extraParams;
		if (existingForm) {
			params = existingForm;
		}
		if (!paramsData || !requiredParams) {
			return params;
		}
		if (params == null) {
			params = {};
		}
		for (let i = 0; i < requiredParams.length; i ++) {
			let name = requiredParams[i];
			if (paramsData[name] === undefined) {
				console.error('Unable to find required property \'' + name + '\' from params data!');
				continue;
			}
			else {
				params[name] = paramsData[name];
			}
		}
		return params;
	},
	// 从查询结果中解析单记录数据对象
	parseSingleItemResult(result) {
		let data = result;
		if(typeof data == 'string') {
			if (data == '') {
				data = null;
			}
			else {
				data = JSON.parse(data);
			}
		}
		// 如果返回的是一个数组，则取数组的第一个元素
		if (data.length > 0) {
			data = data[0];
		}
		// 如果是空数组，则为null
		else if (data.length == 0) {
			data = null;
		}
		return data;
	},
	/*
	 * 对服务器返回的一条记录数据进行格式化准备
	 */
	normalizeData(model, data) {
		let fields = model.fields;
		for (let i = 0; i < fields.length; i ++) {
			let field = fields[i];
			let type = field.type;
			let tableName = field.tableName;
			if (field.builder) {
				field.builder(data);
			}
			else if (type == Fields.types.date && data[tableName] !== undefined) {
				data[tableName] = TimeUtils.toDate(data[tableName]);
			}
			else if (type == Fields.types.number) {
				let value = data[tableName];
				if (typeof(value) == 'string' && value != '') {
					value = Number(value);
				}
				if (field.multiplier && !data['__' + tableName]) {
					value = value / field.multiplier;
					// 用于标记该字段已被格式化
					data['__' + tableName] = true;
				}
				data[tableName] = value;
			}
			else if (type == Fields.types.images) {
				let original = FormUtils.parseArray(data[tableName]);
				let items = [];
				for (let i in original) {
					let item = original[i];
					let isObject = item instanceof Object;
					if (isObject && !item.original) {
						console.warn('Found invalid image item', item);
						continue;
					} 
					let originalObject = isObject ? item.original : item;
					items.push({
						original: originalObject,
						thumb: isObject && item.thumb ? item.thumb : OSS.signWithStyle(originalObject, 'web-thumb'),
						full: isObject && item.full ? item.full : OSS.signWithStyle(originalObject, 'web-full')
					});
				}
				data[tableName] = items;
				// 生成一个原始数据数组
				if (!data[field.name]) {
					let originalItems = [];
					for (let i = 0; i < items.length; i ++) {
						let item = items[i];
						if (item instanceof Object) {
							originalItems.push(item.original);
						}
						else {
							originalItems.push(item);
						}
					}
					data[field.name] = originalItems;
				}
			}
		}
		return data;
	},
	formatFieldDisplay(data, field) {
		let type = field.type;
		let value = data[field.tableName];
		let display = value;
		if (type == Fields.types.number) {
			if (value != null && (typeof value == 'number' || value != '')) {
				display = this.formatNumber(value, field);
			}
			else {
				display = '';
			}
		}
		else if (type == Fields.types.select) {
			display = this.formatSelect(value, field);
		}
		else if (type == Fields.types.date) {
			display = TimeUtils.format(value, 'date');
		}
		else if (type == Fields.types.images) {
			display = this.formatImages(value);
		}
		else if (type == Fields.types.currency) {
			display = this.formatCurrency(value, field);
		}
		if (field.unit && display !== '') {
			display += field.unit;
		}
		if (field.conditions) {
			for (let i in field.conditions) {
				let condition = field.conditions[i];
				if (condition.value == value) {
					let conditional = '';
					for (let f in condition.fields) {
						conditional += this.formatFieldDisplay(data, condition.fields[f]) + ' ';
					}
					display += ' (' + conditional + ')';
				}
			}
		}
		return display;
	},
	formatNumber(value, field) {
		if (field.multiplier) {
			return value / field.multiplier;
		}
		return value;
	},
	formatCurrency(value, field) {
		return value / 100 + '元';
	},
	formatImages(value, field) {
		if(value == null || typeof value !== 'object' || value.length == 0) {
			return '没有图片';
		}
		return value.length + '张图片';
	},
	formatSelect(value, field) {
		let options = field.options;
		if (options !== undefined && options.length > 0) {
			for (let i = 0; i < options.length; i ++) {
				if (options[i].value == value) {
					return options[i].label;
				}
			}
		}
		return value;
	},

}